﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Time.Model;

namespace Time.App
{
    public partial class CreateUserWindow : Form
    {
        private TimeDataContext db = new TimeDataContext();
        public User User;
        public CreateUserWindow(Form owner)
        {
            this.Owner = owner;
            InitializeComponent();

            List<License> licenses = db.Licenses.OrderBy(l => l.Name).ToList();

            foreach (License license in licenses)
            {
                ComboBoxItem item = new ComboBoxItem { Name = license.Name, Tag = license };
                int index = ddlLicenses.Items.Add(item);
            }
        }

        private void textBox_TextChanged(object sender, EventArgs e)
        {
            btnCreateUser.Enabled =
                (txtEmailAddress.Text.Length > 0
                && txtPassword.Text.Length > 0
                && txtConfirmPassword.Text.Length > 0
                && txtPassword.Text == txtConfirmPassword.Text
                && txtFirstName.Text.Length > 0
                && txtLastName.Text.Length > 0
                && ddlLicenses.SelectedIndex > -1);
        }

        private void btnCreateUser_Click(object sender, EventArgs e)
        {
            try
            {
                ComboBoxItem selectedLicense = ddlLicenses.SelectedItem as ComboBoxItem;
                if (selectedLicense == null) throw new Exception("Unknown license!");

                License license = selectedLicense.Tag as License;
                if (license == null) throw new Exception("Unknown license!");

                ISingleResult<CreateUserResult> res = db.CreateUser(txtEmailAddress.Text.ToLower(), txtPassword.Text, txtFirstName.Text, txtLastName.Text, license.Id, Constants.PASSWORD_SALT);

                if (res.Count() != 1)
                {
                    MessageBox.Show(this, "Could not create user!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
    }

    public class ComboBoxItem : object
    {
        public string Name { get; set; }
        public object Tag { get; set; }

        public override string ToString()
        {
            return Name;
        }
    }
}
